package cn.melon.helper;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 读取和存入缓存的实体类, 但由于存储在文件中, 读取硬盘速度较慢, 尽量存比较重要的内容<br>
 *              不可以直接新建该类的对象, 请使用ICacheHelper接口
 * @author corvo
 */
public class JsonCacheHelper implements ICacheHelper {

    ClassLoader classLoader = getClass().getClassLoader();
    private final String CACHE = classLoader.getResource("cache/cache.json").getFile();

    String fileName;

    public JsonCacheHelper() {
        try {
            fileName = java.net.URLDecoder.decode(CACHE, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getCache(String key) {
        JSONObject json = null;
        String jsonString = null;
        String res = null;

        try {
            jsonString = readFile(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        try {
            json = new JSONObject(jsonString);
            if (json.has(key)) {
                res = json.getString(key);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        
        return res;
    }

    @Override
    public Boolean setCache(String key, String value) {

        JSONObject json = null;
        String jsonString = null;
        Boolean isModify = false;
        try {
            jsonString = readFile(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            json = new JSONObject(jsonString);

            if (json.has(key)) {
                if (!json.getString(key).equals(value)) {
                    isModify = true;
                    json.put(key, value);
                }
            } else {
                json.put(key, value);
            }
            saveString(fileName, json.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        System.out.println(key + value);
        return isModify;
    }

    /**
     * 从文件中读取字符串并保存成String类型
     * @param fileName
     * @return
     * @throws IOException
     *             String
     */
    private String readFile(String fileName) throws IOException {

        BufferedReader reader = new BufferedReader(new FileReader(fileName));
        String line = null;
        StringBuilder builder = new StringBuilder();
        String ls = System.getProperty("line.separator");

        try {
            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(ls);
            }
            return builder.toString();
        } finally {
            reader.close();
        }
    }


    /**
     * 保存字符串到文件中
     * @param fileName
     * @param data void
     */
    private void saveString(String fileName, String data) {
        BufferedWriter writer = null;

        try {
            writer = new BufferedWriter(new FileWriter(fileName));
            writer.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    /*  TODO 删除main函数
    public static void main(String[] args) {
        ICacheHelper helper = new JsonCacheHelper();
        System.out.println("IsModify: " +  helper.setCache("uuid", "2123944"));
        helper.setCache("text", "new_text");
        System.out.println(helper.getCache("uuid"));
    }
    */
}
